package com.dy.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.dy.basic.constant.BaseConstants;
import com.dy.basic.service.impl.BaseServiceImpl;
import com.dy.basic.util.AjaxResult;
import com.dy.basic.util.BusinessException;
import com.dy.basic.util.HttpUtil;
import com.dy.basic.util.StrUtils;
import com.dy.system.mapper.MenuMapper;
import com.dy.system.mapper.PermissionMapper;
import com.dy.user.domain.Logininfo;
import com.dy.user.domain.User;
import com.dy.user.domain.Wxuser;
import com.dy.user.dto.PhoneRegisterFormDto;
import com.dy.user.dto.WechatDto;
import com.dy.user.mapper.LogininfoMapper;
import com.dy.user.mapper.UserMapper;
import com.dy.user.mapper.WxuserMapper;
import com.dy.user.service.IWxuserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dayong
 * @since 2023-03-07
 */
@Service
public class WxuserServiceImpl extends BaseServiceImpl<Wxuser> implements IWxuserService {

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Value("${jwt.rsa.pri}")
    private String jwtRsaPrivate;

    @Autowired
    private LogininfoServiceImpl logininfoService;

    /**
     * 微信扫码登录
     * @param wechatDto
     * @return
     */
    @Override
    public AjaxResult wechat(WechatDto wechatDto) {
        // 检验参数
        // 发起第二次请求获取token和openId
        String tokenUrl = String.format(BaseConstants.WechatConstant.TOKEN_URL,BaseConstants.WechatConstant.APPID,BaseConstants.WechatConstant.SECRET,wechatDto.getCode());
        // 通过openId去查询t_wxuser表中有没有数据
        String jsonStr = HttpUtil.httpGet(tokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");
        Wxuser wxuser = wxuserMapper.getByOpenId(openid);
        // 有数据就直接把token，logininfo数据存到map中并返回
        if (null != wxuser && null != wxuser.getUserId()){
            // 查询logininfo的数据根据userId
            Logininfo logininfo = userMapper.findLogininfoById(wxuser.getUserId());
            // 生成随机数UUID
//            String UUID = StrUtils.getComplexRandomString(9);
//            // 数据保存到Redis设置保存时间
//            redisTemplate.opsForValue().set(UUID,logininfo,30, TimeUnit.MINUTES);
//            HashMap<String, Object> objectObjectHashMap = new HashMap<>();
//            objectObjectHashMap.put("UUID",UUID);
//            objectObjectHashMap.put("logininfo",logininfo);
            HashMap<String, Object> stringObjectHashMap = logininfoService.loginSuccessJwtHandler(logininfo);
            return AjaxResult.me().success(stringObjectHashMap);
        } else {
            // 没有的话就返回noRegister让用户去数据绑定页面success:false   msg:noRegister resultObj:accessToken=xxx&openId=xxx
            String resObj = "?accessToken="+token + "&openid=" + openid;
            return AjaxResult.me().setSuccess(false).setMsg("noRegister").setResultObj(resObj);
        }
    }

    /**
     * 强制绑定的界面
     * @param phoneRegisterFormDto
     * @return
     */
    @Override
    public AjaxResult wechatBinder(PhoneRegisterFormDto phoneRegisterFormDto) {
        // 校验参数
        // 判断验证码是否输入正确
        String code = (String) redisTemplate.opsForValue().get(String.format(BaseConstants.BUSINESS_BINDER_PREFIX, phoneRegisterFormDto.getPhone()));
        if (!code.equals(phoneRegisterFormDto.getVerifyCode())){
            throw new BusinessException("验证码输入不正确");
        }
        // 调第三次接口得到wxuser接口
        String thirdUrl = String.format(BaseConstants.BUSINESS_Third_PREFIX,phoneRegisterFormDto.getAccessToken(),phoneRegisterFormDto.getOpenId());
        String jsonStr = HttpUtil.httpGet(thirdUrl);
        Wxuser wxuser = JSONObject.parseObject(jsonStr,Wxuser.class);
        // 查询在user,logininfo表中有没有数据
        Logininfo logininfo = logininfoMapper.findByPhone(phoneRegisterFormDto.getPhone());
        User user = userMapper.findByPhone(phoneRegisterFormDto.getPhone());
//        String token = StrUtils.getComplexRandomString(9);
        if (null != user && null != logininfo){
            // 有的话就只添加wxuser
            wxuser.setUserId(user.getId());
            wxuserMapper.add(wxuser);
        } else {
            // 没有的话就添加三张表的数据
            logininfo = new Logininfo();
            logininfo.setUsername(wxuser.getNickname());
            logininfo.setPhone(phoneRegisterFormDto.getPhone());
            logininfoMapper.add(logininfo);

            user = new User();
            BeanUtils.copyProperties(logininfo,user);
            user.setLogininfoId(logininfo.getId());
            userMapper.add(user);

            wxuser.setUserId(user.getId());
            wxuserMapper.add(wxuser);
        }
//        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
//        objectObjectHashMap.put("token",token);
//        objectObjectHashMap.put("logininfo",logininfo);
        HashMap<String, Object> stringObjectHashMap = logininfoService.loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().success(stringObjectHashMap);
    }
}
